
// JavaScript Document

Autocompleter.InviteePicker = Class.create();
Autocompleter.InviteePicker.prototype = Object.extend(new Autocompleter.Base(), {
  initialize: function(element, update, insName, contextPath, propertyUser, propertyGroup, propertyRole, populator, defaultValues, view, maxLength, options ) {
    this.baseInitialize(element, update, options);
    this.options.array_id = new Array(0);
    this.options.array_type = new Array(0);
    this.options.array = new Array(0);
    this.options.array_email = new Array(0);

    this.populator = populator;
    //alert("initialize....");

		this.options.onShow  = 	function(element, update){ 
															if(!update.style.position || update.style.position=='absolute') {
																update.style.position = 'absolute';
																Position.clone(element, update, {
																	setHeight: false,
																	setWidth: false,
																	offsetTop: element.offsetHeight
																});
															}
															Effect.Appear(update,{duration:0.15});
														};
		
		this.element = $(element);
		this.insName = insName;
		this.controlbox = $(insName + "_controlbox");
		this.container = $(insName + "_entity_container");
		this.contextPath = contextPath;
		this.propertyUser = propertyUser;
		this.propertyGroup = propertyGroup;
		this.propertyRole = propertyRole;
		this.view = view;
        this.maxLength = maxLength;
		
		this.oldValue = '';
		this.keyDownFlag = '';
		this.trueValue = '';

		if(defaultValues){
	      var ins = [];		  
		  for(var z=0; z < defaultValues.length; z++){
		    var entityArray = defaultValues[z]; 
		    //setDefaultEntity(defaultValues[z]);
            var entityId    = entityArray[0];
            var entityType  = entityArray[1];
            var entityName  = entityArray[2];
            var entityEmail = entityArray[3];
  	        var imgPath = null;
  	        var hiddenInput = null;		
  	        if (this.trueValue != "") {
  	        	if (entityType == 'U') {
  	        		imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconUser.gif\" ";
  	        		hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyUser + "\" value=\"" + entityId + "\" />"
  	        	} else if (entityType == 'G') {
  	        		imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconGroup.gif\" ";
  	        		hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyGroup + "\" value=\"" + entityId + "\" />"
  	        	} else if (entityType == 'R') {
  	        		imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconRole.gif\" ";
  	        		hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyRole + "\" value=\"" + entityId + "\" />"
  	        	}
  	        	
  	        	ins.push("<div id='" + this.insName + "_" + entityType + "_" + entityId + "' " + (entityEmail==null?" ":("title='" + entityEmail + "' ")) + 
  	        				" class=\"outInvitee\" " + 
  	        				" name=" + this.insName + "_" + entityType + " " +
  	        				" onmousedown=\"entityClick('" + this.insName + "',this,event)\" >" + 
  	        				imgPath + " />" +
  	        				entityName + 
  	        				"<img src=\"" + this.contextPath + "/theme/pref2/img/common/arrow_down.gif\">" +
  	        				hiddenInput + 
  	        				"<input type=\"hidden\" id=\"" + this.element.id + entityType + entityId + "\" />" +
  	        				"</div>");
  	        } else {
  	        	if (entityType == 'U') {
  	        		imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconUser.gif\" ";
  	        		hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyUser + "\" value=\"" + entityId + "\" />"
  	        	} else if (entityType == 'G') {
  	        		imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconGroup.gif\" ";
  	        		hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyGroup + "\" value=\"" + entityId + "\" />"
  	        	} else if (entityType == 'R') {
  	        		imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconRole.gif\" ";
  	        		hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyRole + "\" value=\"" + entityId + "\" />"
  	        	}
  	        	
  	        	ins.push("<div id='" + this.insName + "_" + entityType + "_" + entityId + "' " + (entityEmail==null?" ":("title='" + entityEmail + "' ")) + 
  	        				" class=\"outInvitee\" " + 
  	        				" name=" + this.insName + "_" + entityType + " " +
  	        				" onmousedown=\"entityClick('" + this.insName + "',this,event)\" >" + 
  	        				imgPath + " />" +
  	        				entityName + 
  	        				"<img src=\"" + this.contextPath + "/theme/pref2/img/common/arrow_down.gif\">" +
  	        				hiddenInput + 
  	        				"<input type=\"hidden\" id=\"" + this.element.id + entityType + entityId + "\" />" +
  	        				"</div>");  	        				
  	        }		      	          	          	        
		  }	
		  this.container.innerHTML = this.container.innerHTML + ins.join('');
		}
		Event.observe(this.element, "focus", this.onFocus.bindAsEventListener(this));
		Event.observe(this.element, "keydown", this.onKeyDown.bindAsEventListener(this));
		Event.observe(this.element, "keyup", this.onKeyUp.bindAsEventListener(this));
	
  },
	
  // called by the autocompleter on an event.
  getUpdatedChoices: function() {
    this.populator(this, this.getToken()); // this is the populator specified in the constructor.
  },

  updateChoices: function(choices) {
    if (choices!=null&&choices!=""){
      if(!this.changed && this.hasFocus) {
        this.update.innerHTML = choices;
        Element.cleanWhitespace(this.update);
        Element.cleanWhitespace(this.update.firstChild);

        if(this.update.firstChild && this.update.firstChild.childNodes) {
          this.entryCount = 
            this.update.firstChild.childNodes.length;
          for (var i = 0; i < this.entryCount; i++) {
            var entry = this.getEntry(i);
            entry.autocompleteIndex = i;
            this.addObservers(entry);
          }
        } else { 
          this.entryCount = 0;
        }

        this.stopIndicator();
        this.index = 0;
        
        if(this.entryCount==1 && this.options.autoSelect) {
          this.selectEntry();
          this.hide();
        } else {
          this.render();
        }
      }
    } else {
      this.update.innerHTML = "";
    }
  },

  // should be called by the populator (specified in the constructor)
  setChoices: function(array) {
    //this.options.array = array;
    //alert("start setChoices()\n" + array);
    this.options.array_id = array[0];
    this.options.array_type = array[1];
    this.options.array = array[2];
    this.options.array_email = array[3];
    /*
    this.options.array_id = array[4];
    this.options.array_type = array[5];
    this.options.array = array[6];
    this.options.array_email = array[7];
    */
    //var temp = this.options.selector(this);
    //if (temp!=null&&temp!=""){
    //  this.updateChoices(temp);
    //}
    this.updateChoices(this.options.selector(this));

		this.trueValue = this.element.value;
		var reg = eval("/^" + this.formatToReg(this.element.value) + "/gi");
		var userTags = document.getElementsByName(this.propertyUser);
		var groupTags = document.getElementsByName(this.propertyGroup);
		var roleTags = document.getElementsByName(this.propertyRole);
    /*
			for (var a = 0; a<userTags.length; a++){
			}
    */
		for (var i=0; i < this.options.array.length; i++){
			var isContinue = false;
			for (var a = 0; userTags && a<userTags.length; a++){
				if (userTags[a].value == this.options.array_id[i] && "U" == this.options.array_type[i]){
					isContinue = true;
					break;
				}
			}
			if (isContinue){
				continue;	
			}
			for (var a = 0; groupTags && a<groupTags.length; a++){
				if (groupTags[a].value == this.options.array_id[i] && "G" == this.options.array_type[i]){
					isContinue = true;
					break;
				}
			}
			if (isContinue){
				continue;	
			}
			for (var a = 0; roleTags && a<roleTags.length; a++){
				if (roleTags[a].value == this.options.array_id[i] && "R" == this.options.array_type[i]){
					isContinue = true;
					break;
				}
			}
			if (isContinue){
				continue;	
			}
			if (reg.test(this.options.array[i])){
				this.keyDownFlag = 'n';
				return ;
			}
			var testTemp = this.options.array[i].split(' ');
			for(var j=1; j<testTemp.length; j++){
				if (reg.test(testTemp[j])){
					this.keyDownFlag = 'n';
					return;	
				}
			}
		}
    if (this.oldValue!=this.element.value){
      this.element.value = this.oldValue;
      this.trueValue = this.element.value;
    }

  },
	
  /*
  getUpdatedChoices: function() {
    this.updateChoices(this.options.selector(this));
  },
  */
	
	
	formatToReg: function(temp){
		var re = temp.replace(/\\/gi,"\\\\").replace(/\//gi,"\\/").replace(/\$/gi,"\\$").replace(/\(/gi,"\\(").replace(/\)/gi,"\\)").replace(/\*/gi,"\\*").replace(/\+/gi,"\\+").replace(/\./gi,"\\.").replace(/\[/gi,"\\[").replace(/\]/gi,"\\]").replace(/\?/gi,"\\?").replace(/\^/gi,"\\^").replace(/\{/gi,"\\{").replace(/\}/gi,"\\}").replace(/\|/gi,"\\|");		
		return re;
	},
	
	
	onKeyUp: function(event){
		this.keyDownFlag = 'n';
	},
	
	onKeyDown: function(event){
		if (this.keyDownFlag == 'n'){
			this.oldValue = this.element.value;
			this.keyDownFlag = 'y';
		}
	},
	
	onFocus: function(event){
		this.trueValue = this.element.value;
		this.oldValue = this.element.value;
		//if (this.element.value == "" && this.options.array.length > 0 ) {
		if (this.element.value == "") {
			this.hasFocus = true;
      /*
			var temp = this.options.selector(this);
			if (temp!=null&&temp!=""){
	    	this.updateChoices(temp);
				this.show(); 
			}
      */
      this.getUpdatedChoices();
      var temp = this.options.selector(this);
      if (temp!=null&&temp!=""){
				this.show(); 
			}
		}
	},
	
	deleteLastEntity: function() {
		if (this.container.lastChild != null) {
			this.container.removeChild(this.container.lastChild);
		}
	},
	
  onKeyPress: function(event) {
		if (event.keyCode == 8 && this.element.value == ""){
		 	this.deleteLastEntity();
			this.hide();
    	//this.updateChoices(this.options.selector(this));
      this.getUpdatedChoices();
		}
    if(this.active){
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntity();
				 if (this.options.onSelect) {
						eval(this.options.onSelect + "(this.getEntry(this.index))"); 
				 }
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
      }
		}else{ 
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
         (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;
		}

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) {
			clearTimeout(this.observer);
		}
    this.observer = setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
		
  },
	
  selectEntity: function() {
    this.active = false;
    var n1 = 0;
    var n2 = 0;
    var n3 = 0;
    if (document.getElementsByName(this.propertyUser)){
      n1 = document.getElementsByName(this.propertyUser).length;
    }
    if (document.getElementsByName(this.propertyGroup)){
      n2 = document.getElementsByName(this.propertyGroup).length;
    }
    if (document.getElementsByName(this.propertyRole)){
      n3 = document.getElementsByName(this.propertyRole).length;
    }
       //alert(parseInt(n1+n2+n3)<this.maxLength);
    if (parseInt(n1+n2+n3)<this.maxLength || !this.maxLength){
		  this.container.innerHTML = this.container.innerHTML + this.getSelectEntity();
    }
		this.element.value = "";
  },
	
	getSelectEntity: function() {	    
		//selectEntry = this.getCurrentEntry()
		var idx = this.getCurrentEntry().innerHTML.substring(this.getCurrentEntry().innerHTML.lastIndexOf("indexS")+6,this.getCurrentEntry().innerHTML.lastIndexOf("indexE"));
		var ins = [];
		var imgPath = null;
		var hiddenInput = null;
		//if (this.element.value != "") {
		if (this.trueValue != "") {
			if (this.options.array_type[idx] == 'U') {
				imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconUser.gif\" ";
				hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyUser + "\" value=\"" + this.options.array_id[idx] + "\" />"
			} else if (this.options.array_type[idx] == 'G') {
				imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconGroup.gif\" ";
				hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyGroup + "\" value=\"" + this.options.array_id[idx] + "\" />"
			} else if (this.options.array_type[idx] == 'R') {
				imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconRole.gif\" ";
				hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyRole + "\" value=\"" + this.options.array_id[idx] + "\" />"
			}
			
			ins.push("<div id='" + this.insName + "_" + this.options.array_type[idx] + "_" + this.options.array_id[idx] + "' " + (this.options.array_email[idx]==null?" ":("title='" + this.options.array_email[idx] + "' ")) + // " title='" + (this.options.array_email[idx]==null?"":(this.options.array_email[idx]+"\n")) + "'" +
						" class=\"outInvitee\" " + 
						" name=" + this.insName + "_" + this.options.array_type[idx] + " " +
						" onmousedown=\"entityClick('" + this.insName + "',this,event)\" >" + 
						imgPath + " />" +
						this.options.array[idx] + 
						"<img src=\"" + this.contextPath + "/theme/pref2/img/common/arrow_down.gif\">" +
						hiddenInput + 
						"<input type=\"hidden\" id=\"" + this.element.id + this.options.array_type[idx] + this.options.array_id[idx] + "\" />" +
						"</div>");
		} else {
			if (this.options.array_type[idx] == 'U') {
				imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconUser.gif\" ";
				hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyUser + "\" value=\"" + this.options.array_id[idx] + "\" />"
			} else if (this.options.array_type[idx] == 'G') {
				imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconGroup.gif\" ";
				hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyGroup + "\" value=\"" + this.options.array_id[idx] + "\" />"
			} else if (this.options.array_type[idx] == 'R') {
				imgPath = " <img src=\"" + this.contextPath + "/theme/pref2/img/common/IconRole.gif\" ";
				hiddenInput = "<input type=\"hidden\" name=\"" + this.propertyRole + "\" value=\"" + this.options.array_id[idx] + "\" />"
			}
			
			ins.push("<div id='" + this.insName + "_" + this.options.array_type[idx] + "_" + this.options.array_id[idx] + "' " + (this.options.array_email[idx]==null?" ":("title='" + this.options.array_email[idx] + "' ")) +  //" title='" + (this.options.array_email[idx]==null?"":(this.options.array_email[idx]+"\n")) + "'" +
						" class=\"outInvitee\" " + 
						" name=" + this.insName + "_" + this.options.array_type[idx] + " " +
						" onmousedown=\"entityClick('" + this.insName + "',this,event)\" >" + 
						imgPath + " />" +
						this.options.array[idx] + 
						"<img src=\"" + this.contextPath + "/theme/pref2/img/common/arrow_down.gif\">" +
						hiddenInput + 
						"<input type=\"hidden\" id=\"" + this.element.id + this.options.array_type[idx] + this.options.array_id[idx] + "\" />" +
						"</div>");
		}
		return ins;
	},
	
  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntity();
		 if (this.options.onSelect) {
				eval(this.options.onSelect + "(this.getEntry(this.index))");
		 }
    this.hide();
  },
	
  onObserverEvent: function() {
    this.changed = false;   
    if(this.getToken().length>=this.options.minChars || this.element.value == "") {
      this.startIndicator();
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
  },

  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: false,
      partialChars: 1,
      ignoreCase: true,
      fullSearch: false,
			onReceive: "",
			onSelect: "",
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var partial   = []; // Inside matches
        var entry     = instance.getToken();
        var count     = 0;
				
				if (instance.element.value != "") { 
					for (var i = 0; i < instance.options.array.length &&  
						ret.length < instance.options.choices ; i++) { 
	
						var elem = instance.options.array[i];
						var foundPos = instance.options.ignoreCase ? 
							elem.toLowerCase().indexOf(entry.toLowerCase()) : 
							elem.indexOf(entry);
						/*
						var secondPos = instance.options.ignoreCase ?
							elem.toLowerCase().indexOf((" "+entry).toLowerCase()) :
							elem.indexOf(" "+entry);
						*/
	
						while (foundPos != -1 || entry == "") {
							if ((foundPos == 0 && elem.length >= entry.length)) { 
								/*
								if (secondPos != -1) {
									foundPos = secondPos + 1;	
								}
								*/
								if ($(instance.element.id + instance.options.array_type[i] + instance.options.array_id[i]) != null) {
									break;	
								}
								/*
								ret.push("<li class='selectLi'><strong>" + elem.substr(0, entry.length) + "</strong>" + 
									elem.substr(entry.length) + "</li>");
								*/
								var imgPath = null;
								if (instance.options.array_type[i]=="U"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconUser.gif"	;
								} else if (instance.options.array_type[i]=="G"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconGroup.gif";
								} else if (instance.options.array_type[i]=="R"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconRole.gif";
								}
								ret.push("<li class='selectLi'><img src='" + imgPath + "' style='width:14px; height:14px;'></img>&nbsp;&nbsp;" + elem.substr(0, foundPos) + "<strong>" +
									elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
									foundPos + entry.length) + (instance.options.array_email[i]==null||instance.options.array_email[i]==""?"":" &lt;"+instance.options.array_email[i] + "&gt;") + 
									"<input type=\"hidden\" id=\"index\" value=\"indexS" + i + "indexE\" />" + 
									"</li>");
								break;
							} else if (entry.length >= instance.options.partialChars && 
								instance.options.partialSearch && foundPos != -1) {
								//alert(instance.options.fullSearch);
								if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
									partial.push("<li class='selectLi'><img src='IconGroup.gif' style='width:14px; height:14px;'></img>" + elem.substr(0, foundPos) + "<strong>" +
										elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
										foundPos + entry.length) + "</li>");
									break;
								}
							}
	
							foundPos = instance.options.ignoreCase ? 
								elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
								elem.indexOf(entry, foundPos + 1);
							/*	
							secondPos = instance.options.ignoreCase ?
								elem.toLowerCase().indexOf((" "+entry).toLowerCase()) :
								elem.indexOf(" "+entry);
							*/
	
						}
					}
					
					
					for (var i = 0; i < instance.options.array.length &&  
						ret.length < instance.options.choices ; i++) { 
	
						var elem = instance.options.array[i];
						var foundPos = instance.options.ignoreCase ? 
							elem.toLowerCase().indexOf(entry.toLowerCase()) : 
							elem.indexOf(entry);
							
						var secondPos = instance.options.ignoreCase ?
							elem.toLowerCase().indexOf((" "+entry).toLowerCase()) :
							elem.indexOf(" "+entry);
							
	
						while (foundPos != -1 || entry == "") {
							if (foundPos == 0){
								break;	
							}
							if ((foundPos == 0 && elem.length != entry.length) || secondPos != -1 || entry == "") { 
								if (secondPos != -1) {
									foundPos = secondPos + 1;	
								}
								
								if ($(instance.element.id + instance.options.array_type[i] + instance.options.array_id[i]) != null) {
									break;	
								}
								/*
								ret.push("<li class='selectLi'><strong>" + elem.substr(0, entry.length) + "</strong>" + 
									elem.substr(entry.length) + "</li>");
								*/
								var imgPath = null;
								if (instance.options.array_type[i]=="U"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconUser.gif"	;
								} else if (instance.options.array_type[i]=="G"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconGroup.gif";
								} else if (instance.options.array_type[i]=="R"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconRole.gif";
								}
								ret.push("<li class='selectLi'><img src='" + imgPath + "' style='width:14px; height:14px;'></img>&nbsp;&nbsp;" + elem.substr(0, foundPos) + "<strong>" +
									elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
									foundPos + entry.length) + (instance.options.array_email[i]==null||instance.options.array_email[i]==""?"":" &lt;"+instance.options.array_email[i] + "&gt;") + 
									"<input type=\"hidden\" id=\"index\" value=\"indexS" + i + "indexE\" />" + 
									"</li>");
								break;
							} else if (entry.length >= instance.options.partialChars && 
								instance.options.partialSearch && foundPos != -1) {
								//alert(instance.options.fullSearch);
								if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
									partial.push("<li class='selectLi'><img src='IconGroup.gif' style='width:14px; height:14px;'></img>" + elem.substr(0, foundPos) + "<strong>" +
										elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
										foundPos + entry.length) + "</li>");
									break;
								}
							}
	
							foundPos = instance.options.ignoreCase ? 
								elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
								elem.indexOf(entry, foundPos + 1);
								
							secondPos = instance.options.ignoreCase ?
								elem.toLowerCase().indexOf((" "+entry).toLowerCase()) :
								elem.indexOf(" "+entry);
								
	
						}
					}
					
					if (partial.length)
						ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
					return "<ul class='selectUi'>" + ret.join('') + "</ul>";
				} else {
					for (var i = 0; i < instance.options.array.length &&  
						ret.length < instance.options.choices ; i++) { 
	
						var elem = instance.options.array[i];
						var foundPos = instance.options.ignoreCase ? 
							elem.toLowerCase().indexOf(entry.toLowerCase()) : 
							elem.indexOf(entry);
						
						var secondPos = instance.options.ignoreCase ?
							elem.toLowerCase().indexOf((" "+entry).toLowerCase()) :
							elem.indexOf(" "+entry);
	
						while (foundPos != -1 || entry == "") {
							if ((foundPos == 0 && elem.length != entry.length) || secondPos != -1 || entry == "") { 
								if (secondPos != -1) {
									foundPos = secondPos + 1;	
								}
								if ($(instance.element.id + instance.options.array_type[i] + instance.options.array_id[i]) != null) {
									break;	
								}
								/*
								ret.push("<li class='selectLi'><strong>" + elem.substr(0, entry.length) + "</strong>" + 
									elem.substr(entry.length) + "</li>");
								*/
								var imgPath = null;
								if (instance.options.array_type[i]=="U"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconUser.gif"	;
								} else if (instance.options.array_type[i]=="G"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconGroup.gif";
								} else if (instance.options.array_type[i]=="R"){
									imgPath = instance.contextPath + "/theme/pref2/img/common/IconRole.gif";
								}
								ret.push("<li class='selectLi'><img src='" + imgPath + "' style='width:14px; height:14px;'></img>&nbsp;&nbsp;" + elem.substr(0, foundPos) + "<strong>" +
									elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
									foundPos + entry.length) + (instance.options.array_email[i]==null||instance.options.array_email[i]==""?"":" &lt;"+instance.options.array_email[i] + "&gt;") + 
									"<input type=\"hidden\" id=\"index\" value=\"indexS" + i + "indexE\" />" + 
									"</li>");
								break;
							} else if (entry.length >= instance.options.partialChars && 
								instance.options.partialSearch && foundPos != -1) {
								//alert(instance.options.fullSearch);
								if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
									partial.push("<li class='selectLi'><img src='IconGroup.gif' style='width:14px; height:14px;'></img>" + elem.substr(0, foundPos) + "<strong>" +
										elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
										foundPos + entry.length) + "</li>");
									break;
								}
							}
	
							foundPos = instance.options.ignoreCase ? 
								elem.toLowerCase().indexOf((" "+entry).toLowerCase(), foundPos + 1) : 
								elem.indexOf(" "+entry, foundPos + 1);
								
							secondPos = instance.options.ignoreCase ?
								elem.toLowerCase().indexOf((" "+entry).toLowerCase()) :
								elem.indexOf(" "+entry);
	
						}
					}
					
					if (partial.length)
						ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
					if (ret.join('')==""){
						return null;	
					} else {
						return "<ul class='selectUi'>" + ret.join('') + "</ul>";
					}
				}
      }
    }, options || {});
  }
});



	var m_on = null;
	var m_click = null;

	var dlg;

	function delEntity(entity){
		if (m_on!=null){
			switch(event.keyCode) {
				case 8:
				case 46:
					entity.removeChild(m_on);
					m_on=null;
			}
		}
	}
	function overEntity(entity){
		entity.className = "treeClick";
		m_on = entity;
	}
	function outEntity(entity){
		entity.className = "treeOut";
		m_on = null;
	}
	function moveCur(name){
			document.getElementById(name).scrollTop = document.getElementById(name).scrollHeight;
			document.getElementById(name+"_Input_text").focus();
	}
	function dbclick(name,entity){
		document.getElementById(name).removeChild(entity);
	}
	function mouseCoords(ev){
			if(ev.pageX || ev.pageY){
					return {x:ev.pageX, y:ev.pageY};
			}
			return {
					x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
					y:ev.clientY + document.body.scrollTop  - document.body.clientTop
			};
	}
	function entityClick(name,entity,ev){
		controlBoxId = name + "_controlbox";
		closeControlBox(controlBoxId);
		m_click = entity;
		
		ev = ev || window.event;
        var mousePos = mouseCoords(ev);
		
		document.getElementById(controlBoxId).style.top = mousePos.y + "px";
		document.getElementById(controlBoxId).style.left = mousePos.x + "px";
		document.getElementById(controlBoxId).style.display = "";
	}
	function deleteEntity(name){
		containerId = name + "_entity_container";
		controlBoxId = name + "_controlbox";
		try{
			if (m_click!=null){
				document.getElementById(containerId).removeChild(m_click);
			}
			closeControlBox(controlBoxId);
		} catch (e){
			closeControlBox(controlBoxId);
		}
	}
	function deleteAll(name){
		containerId = name + "_entity_container";
		controlBoxId = name + "_controlbox";
		document.getElementById(containerId).innerHTML = "";
		closeControlBox(controlBoxId);
	}
	function closeControlBox(controlBoxId){
		document.getElementById(controlBoxId).style.display = "none";
		m_click = null;
	}
	function showDialog(name){
		var backGroundId = name + "_showDialog";
		var innerContentPane = FindObj(name + "_tabs_container");
		
		innerContentPane.style.width = GlobalVariable.getWindowAvailWidth() * 0.8 + "px";
		innerContentPane.style.height = GlobalVariable.getWindowAvailHeight() * 0.9 + "px";

		dlg = dojo.widget.byId(backGroundId);
		document.getElementsByTagName("body")[0].scroll="no";
		dlg.show();
	}
	function hideDialog(name){
		var backGroundId = name + "_showDialog";
		var inviteeDlg = dojo.widget.byId(backGroundId);
		document.getElementsByTagName("body")[0].scroll="yes";
		inviteeDlg.hide();
		// showInviteePickerTabs(name,"Group");
	}
	function showInviteePickerTabs(name,tabName){
		var tab_group_id = name + "_tab_group";
		var tab_role_id = name + "_tab_role";
		var tab_staffhierarchy_id = name + "_tab_staffhierarchy";
		var tab_group_font_id = name + "_tab_group_font";
		var tab_role_font_id = name + "_tab_role_font";
		var tab_staffhierarchy_font_id = name + "_tab_staffhierarchy_font";
		if (tabName == "Group") {
			document.getElementById(tab_group_id).style["display"] = "";
			document.getElementById(tab_role_id).style["display"] = "none";
			document.getElementById(tab_staffhierarchy_id).style["display"] = "none";
			document.getElementById(tab_group_font_id).style["color"] = "#0000aa";
			document.getElementById(tab_role_font_id).style["color"] = "#999999";
			document.getElementById(tab_staffhierarchy_font_id).style["color"] = "#999999";
		} else if (tabName == "Role") {
			document.getElementById(tab_group_id).style["display"] = "none";
			document.getElementById(tab_role_id).style["display"] = "";
			document.getElementById(tab_staffhierarchy_id).style["display"] = "none";
			document.getElementById(tab_group_font_id).style["color"] = "#999999";
			document.getElementById(tab_role_font_id).style["color"] = "#0000aa";
			document.getElementById(tab_staffhierarchy_font_id).style["color"] = "#999999";
		} else if (tabName == "StaffHierarchy") {
			document.getElementById(tab_group_id).style["display"] = "none";
			document.getElementById(tab_role_id).style["display"] = "none";
			document.getElementById(tab_staffhierarchy_id).style["display"] = "";
			document.getElementById(tab_group_font_id).style["color"] = "#999999";
			document.getElementById(tab_role_font_id).style["color"] = "#999999";

			document.getElementById(tab_staffhierarchy_font_id).style["color"] = "#0000aa";
		}
	}
	function rowOver(theRow,i){
		theRow.className = "rowOver";
	}
	function rowOut(theRow,i){
		if (i%2==0){
			theRow.className = "listContent1";
		} else {
			theRow.className = "listContent0";
		}
	}
  function changeView(prefixName) {
    document.getElementById(prefixName+"_tab_group").style.display="none";
    document.getElementById(prefixName+"_tab_role").style.display="none";
    document.getElementById(prefixName+"_tab_staffhierarchy").style.display="none";
    var showType = document.getElementById(prefixName+"ViewType").value;
    if ("G"==showType) {
      document.getElementById(prefixName+"_tab_group").style.display="";
    } else if ("R"==showType) {
      document.getElementById(prefixName+"_tab_role").style.display="";
    } else if ("S"==showType) {
      document.getElementById(prefixName+"_tab_staffhierarchy").style.display="";
    }
  }